/*
 * @depends component.js, Panel.js
 */
QFinance.component.ExpensesAndIncomesByCategoryPanel = Ext.extend( QFinance.ui.Panel, {
    // Localization
    updateText: 'Update',
    optionsText: 'Options',
    accountText: 'Account',
    allTimeText: 'All time',
    past30DaysText: 'Past 30 days',
    past60DaysText: 'Past 60 days',
    thisMonthText: 'This month',
    thisYearText: 'This year',
    customText: 'Custom',
    rangeText: 'Range',
    bothText: 'Both',
    incomeText: 'Income',
    expenseText: 'Expense',
    typeText: 'Type',
    emptyResultText: 'There are no transactions within the chosen options',
	
    // Components
    store: null,
    accountsStore: null,
    rangeCompositeField: null,
    formPanel: null,
    categoriesEditPanel: null,
    accountCombo: null,
    rangeCombo: null,
    typeCombo: null,
	
    constructor: function(config) {
        Ext.apply(this, config);
		
        this.store = new Ext.data.DirectStore({
            autoLoad: false,
            idProperty: 'id',
            root: 'data',
            successProperty: 'success',
            paramsAsHash: false,
            paramOrder: [ 'options', 'accountID', 'parentCategoryID' ],
            baseParams: {
                options: null, 
                accountID: null, 
                parentCategoryID: null
            },
            api: {
                read: QFinance.Remoting.ExpensesAndIncomesByCategoryPanelAction.getExpensesAndIncomesByCategory
            },
            fields: [
            'categoryName',
            'value'
            ],
            listeners: {
                scope: this,
                beforeload: function(store, options) {
                    store.id = this.getProcessStatusManager().start([this]);
                },				
                load: function(store, records, options) {					
                    if (records.length == 0) {
                        this.getProcessStatusManager().success(store.id, this.emptyResultText);
                    } else {
                        this.getProcessStatusManager().success(store.id);
                    }
                },				
                exception: function(dataProxy, type, action, options, response, arg ) {
                    var message = '';
                    var where = '';
                    if (response.result) {
                        message = response.result.message;
                        if (response.result.type == 'exception')
                            where = response.result.where;
                    } else {
                        message = response.message;
                    }
                    this.getProcessStatusManager().error(this.store.id, message);
                    QFinance.service.DeveloperService.log('Store failure: ' + message + ' where\n' + where);
                }
            }				
        });
		
        this.accountStore = new Ext.data.DirectStore({    		
            autoLoad: false,
            directFn: QFinance.Remoting.AccountAction.getByAccountTypePlusAll,
            paramsAsHash: false,            
            idProperty: 'id',
            root: 'data',
            successProperty: 'success',
            paramOrder: [ 'type' ],
            baseParams: {
                type: '1'
            },
            fields: [
            {
                name: 'id',
                type: 'int',
                useNull: true
            },
            {
                name: 'accountName'	    		    
            },
            {
                name: 'accountType'
            }
            ],
            listeners: {
                scope: this,
                beforeload: function(store, options) {
                    store.id = this.getProcessStatusManager().start([this.accountCombo]);                    
                },				
                load: function(store, records, options) {
                    this.getProcessStatusManager().success(store.id);
                    this.accountCombo.setValue(this.accountCombo.store.getAt(0).get(this.accountCombo.id));	
                },				
                exception: function(dataProxy, type, action, options, response, arg ) {
                    var message = '';
                    var where = '';
                    if (response.result) {
                        message = response.result.message;
                        if (response.result.type == 'exception')
                            where = response.result.where;
                    } else {
                        message = response.message;
                    }
                    this.getProcessStatusManager().error(this.accountStore.id, message);
                    QFinance.service.DeveloperService.log('Store failure: ' + message + ' where\n' + where);
                }
            }		
        });		
		
        QFinance.component.ExpensesAndIncomesByCategoryPanel.superclass.constructor.call(this);
    },
	
    initComponent: function() {	
        Ext.apply(this, {
            layout: 'border',
            items: [{
                region: 'north',
                collapsible: true,				
                layout: 'hbox',
                title: this.optionsText,				
                height: 150,
                layoutConfig: {
                    align : 'stretch',
                    pack  : 'start'
                },				
                items: [ this.formPanel = new Ext.form.FormPanel({
                    xtype: 'form',
                    flex: 1,						
                    frame: true,
                    labelWidth: 60,
                    defaults: {
                        anchor: '100%'
                    },
                    items: [ this.accountCombo = new Ext.form.ComboBox({
                        name: 'accountID',
                        store: this.accountStore,
                        fieldLabel: this.accountText,
                        autoSelect: true,
                        editable: false,
                        triggerAction: 'all',		      		    
                        valueField: 'id',
                        displayField: 'accountName',
                        mode: 'local',
                        listeners: {
                            scope: this,
                            select: function(combo, record, index) {
                                this.typeCombo.setDisabled( index == 0 );		              				
                            }
                        }
                    }), this.rangeCombo = new Ext.form.ComboBox({			        	
                        name: 'range',
                        store: [ 
                        [ 1, this.allTimeText ],
                        [ 2, this.past30DaysText ],
                        [ 3, this.past60DaysText ],
                        [ 4, this.thisMonthText ],
                        [ 5, this.thisYearText ],
                        [ 6, this.customText ]
                        ],
                        fieldLabel: this.rangeText,
                        autoSelect: true,		            	
                        editable: false,
                        triggerAction: 'all',		      		    		              	
                        mode: 'local',
                        hiddenName: 'range',
                        value: 1,
                        listeners: {
                            scope: this,
                            select: function(combo, record, index) {		              					              			
                                if (index != 5)
                                    this.rangeCompositeField.items.each(function(f){
                                        f.clearInvalid();
                                    });
		              				
		              			
                                this.rangeCompositeField.setDisabled( index != 5 );
                            }
                        }
                    }), this.rangeCompositeField = new Ext.form.CompositeField({
                        xtype: 'compositefield',
                        disabled: true,
                        defaults: {
                            flex: 1
                        },
                        items: [{
                            xtype: 'datefield',
                            name: 'startDate',
                            id: 'startDate',
                            format: "Y-m-d",
                            vtype: 'daterangecomposite',
                            endDateField: 'endDate',
                            allowBlank: false
                        },
                        {
                            xtype: 'datefield',
                            name : 'endDate',
                            id: 'endDate',
                            format: "Y-m-d",
                            vtype: 'daterangecomposite',
                            startDateField: 'startDate',
                            allowBlank: false
                        }]
                    }), this.typeCombo = new Ext.form.ComboBox({			        	
                        name: 'type',
                        store: [ 
                        [ 1, this.bothText ],
                        [ 2, this.incomeText ],
                        [ 3, this.expenseText ]
                        ],
                        disabled: true,
                        fieldLabel: this.typeText,
                        autoSelect: true,		            	
                        editable: false,
                        triggerAction: 'all',		      		    		              	
                        mode: 'local',
                        hiddenName: 'type',
                        value: 1
                    })]					
                }),this.categoriesEditPanel = new QFinance.component.CategoriesEditPanel({					
                    canAddCategory: false,
                    canEditCategory: false,
                    canRemoveCategory: false,
                    flex: 1,                    
                    statusBar: this.statusBar
                })]
            },{
                xtype: 'highchart',
                store: this.store,
                region: 'center',
                series: [{
                    type: 'pie',
                    dataField: 'value',
                    categorieField: 'categoryName'
                }],                
                chartConfig: {
                    chart: {
                        
                    },
                    plotOptions: {
                        pie: {
                            allowPointSelect: false,
                            cursor: 'pointer',
                            dataLabels: {
                                enabled: true,				                
                                formatter: function() {
                                    return '<b>'+ this.point.name +'</b>: '+ QFinance.moneySymbol + ' ' + Ext.util.Format.number(this.y,QFinance.numberFormat) + ' (' + this.percentage.toFixed(2) + '%)';
                                }
                            }
                        }
                    },
                    title: {
                        text: null
                    },
                    credits: {
                        enabled: false
                    },
                    tooltip: {
                        enabled: false
                    }
                }
            }]
        });		
        QFinance.component.ExpensesAndIncomesByCategoryPanel.superclass.initComponent.call(this);
    },
    
    initStatusBar: function(toolbar) {            	
        toolbar.insert(0, new Ext.Button({
            text: this.updateText,
            scope: this,
            iconCls: 'fugue-arrow-circle',
            handler: function() {
                this.update();
            }
        }));
    },
	
    update: function(scope, callback) {
        if (this.formPanel.getForm().isValid()) {			
            var options = {
                range: this.rangeCombo.getValue(),
                type: this.typeCombo.getValue()
            };
			
            if (options.range == 6) {
                options.startDate = this.formPanel.getForm().findField('startDate').getValue();
                options.endDate = this.formPanel.getForm().findField('endDate').getValue();
            }
			
            var parentCategoryID = null;
            var selectedCategory = this.categoriesEditPanel.getSelectedCategory();
            if (selectedCategory)
                parentCategoryID = selectedCategory.get('id'); 
			
            this.store.setBaseParam('options', options);
            if (this.accountCombo.getValue() > 0)
                this.store.setBaseParam('accountID', this.accountCombo.getValue());
            else
                this.store.setBaseParam('accountID', null);
			
            this.store.setBaseParam('parentCategoryID', parentCategoryID);
            this.store.load({
                scope: scope || null,
                callback: callback || null
            });
        }
    },
    
    autoLoadData: function() {        
        this.body.mask();
        this.accountStore.load({
            scope: this,
            callback: function() {                
                this.update(this, function() {
                    this.categoriesEditPanel.selectCategoryID('root');
                    this.body.unmask();
                });
            } 
        }, this);        
    }
});
Ext.reg('QFinance.component.ExpensesAndIncomesByCategoryPanel', QFinance.component.ExpensesAndIncomesByCategoryPanel);